<?php

namespace Crm\Model;

/**
 * Description of AbsModel
 *
 * @author Su 2015-3-18 by sutroon
 */
abstract class AppbaseModel extends \Think\Model {

    /**
     * 返回数组消息
     * @param mixed $result 数据库执行结果
     * @param mixed $error 错误消息
     * @return array array('status'=>false, 'info'=>'消息')
     * @since 1.0 <2015-3-26> SoChishun Added.
     */
    protected function base_return_array($result, $error = false) {
        return FALSE === $result || is_null($result) ? array('status' => false, 'info' => ($error ? $error : $this->getDbError())) : array('status' => true, 'info' => $result);
    }

    /**
     * 返回分页记录列表
     * @param array $where 查询条件
     * @param string $pager 分页条字符串
     * @param array $options 控制选项
     * @return false|array 成功则返回array,否则返回false
     * @since 1.0 <2015-3-5> by sutroon
     * @example $user->get_paging_list($where,$show,array('ORDERBY' => 'siteID'));
     */
    public function get_paging_list($where, &$pager, $options = array()) {
        $options = array_merge(array('PAGESIZE' => C('USER.PAGE_SIZE'), 'FIELDS' => '*', 'ORDERBY' => 'id desc', 'PAGEPARAMS' => null), $options);
        if ($where) {
            $count = $this->where($where)->count();
        } else {
            $count = $this->count();
        }
        $page = new \Think\Page($count, $options['PAGESIZE'], $options['PAGEPARAMS']);
        $pager = $page->show();
        $params['where'] = $where;
        if ('*' != $options['FIELDS']) {
            $params['field'] = $options['FIELDS'];
        }
        if ($options['ORDERBY']) {
            $params['order'] = $options['ORDERBY'];
        }
        $params['limit'] = $page->firstRow . ',' . $page->listRows;
        return $this->select($params);
    }
    
    /**
     * 返回树形列表或刷新缓存
     * 
     * @param string $key 缓存名称,一般为模型名称/$scope，如Role/$scope或Category/$scope
     * @param string $scope 命名范围,一般为treeselect或treetable
     * @param boolean $refresh 是否强制刷新缓存
     * @since 1.0 <2015-3-25> SoChishun Added.
     * @example return $this->base_get_tree_list('Role/' . $scope, $scope,$refresh);
     */
    public function base_get_tree_list($key,$scope, $refresh = false) {
        if (!$refresh) {
            $list = F($key);
            if ($list) {
                return $list;
            }
        }
        $list = $this->base_get_tree_list_fn($scope, 0);
        F($key, $list);
        return $list;
    }

    /**
     * 返回树形列表的子方法
     * @param string $scope
     * @param int $fid
     * @param string $first_where
     * @return false|array
     * @since 1.0 <2015-3-25> SoChishun Added.
     * @example $list = $this->get_tree_list_fn('main_nav', 0,$where_lv0);
     */
    function base_get_tree_list_fn($scope, $fid, $first_where = '') {
        $list = $this->scope($scope)->where('parent_id=' . $fid . $first_where)->select();
        $new_list = false;
        if ($list) {
            foreach ($list as $row) {
                $list2 = $this->scope($scope)->where('parent_id=' . $row['id'])->select();
                if ($list2) {
                    $row['sub'] = $this->base_get_tree_list_fn($scope, $row['id']);
                }
                $new_list[] = $row;
            }
        }
        return $new_list;
    }

    /**
     * 获取无极json数据
     * 数据格式：[{"id":"1","name":"name1","children":[]}]
     *
     * @param string $table 数据表名称
     * @param array $options 选项,默认array('PARENT_ID' => 0, 'SEARCH' => 'parentID={0}', 'FIELDS' => 'id, name')
     * @param int $deep 级数深度,0=不限,默认0
     * @param int $n 计数器,默认1,无需修改
     * @return string json数据
     * @since 1.0 2014-6-17 by sutroon
     * @example
     *      $str=get_tree_json('tuserpermission', 0,'parentID=',  'id',  'name',$deep=1); // 获取一级数据
     *      $str=get_tree_json('tuserpermission', $fid,'parentID=',  'id',  'name',$deep=0); // 获取从fid后的无极数据
     *      
     * function sofunc_get_tree_json($table, $parent = 0, $search = 'parentID=', $valueName = 'id', $textName = 'name', $deep = 0, $n = 1) {
     */
    function sofunc_get_tree_json($table, $options = array(), $deep = 0, $n = 1) {
        $opts = array('PARENT_ID' => 0, 'SEARCH' => 'parentID={0}', 'FIELDS' => 'id, name');
        if ($options) {
            $opts = array_merge($opts, $options);
        }
        $list = M($table)->field($opts['FIELDS'])->where(str_replace('{0}', $opts['PARENT_ID'], $opts['SEARCH']))->select();
        if (!$list) {
            return '';
        }
        $str = '';
        $valueField = '';
        foreach ($list as $row) {
            if (!$valueField) {
                $keys = array_keys($row);
                $valueField = $keys[0];
                $textField = $keys[1];
            }
            $str .= '{"' . $valueField . '":"' . $row[$valueField] . '","' . $textField . '":"' . $row[$textField] . '"';
            if ($deep > 0 && $deep <= $n) {
                $str1 = '';
            } else {
                $str1 = sofunc_get_tree_json($table, array('PARENT_ID' => $row[$valueField]), $deep, $n + 1);
            }
            if (!$str1) {
                $str .= '},';
                continue;
            }
            $str .= ',"children":' . $str1 . '},';
        }
        return '[' . substr($str, 0, strlen($str) - 1) . ']';
    }

    /**
     * 获取系统扩展字段列表
     * @param string $target 关联对象,如 CUSTOMER、PRODUCT
     * @param int $siteID siteID
     * @return false|array
     * @since 1.0 2014-12-13 by sutroon
     * @example $list = sofunc_get_sys_exfield_list('CUSTOMER', $siteID);
     */
    function sofunc_get_sys_exfield_list($target, $siteID, $display = 1) {
        $where['target'] = $target;
        $where['siteID'] = $siteID;
// $where['isDisplay'] = $display;
        return M('tsys_exfield')->field('`field`, `type`, `length`, `default`, label, inputType, optionalValue, isRequire')->where($where)->order('ordinal, id')->select();
    }

    /**
     * 获取系统扩展字段单条记录数据
     * @param string $target 关联对象,如 CUSTOMER、PRODUCT
     * @param int $siteID siteID
     * @param int $itemID 项目编号
     * @return false|array 成功则返回数组,否则返回false
     * @since 1.0 2014-12-15 by sutroon
     * @example $data = sofunc_get_sys_exfield_data($target, $siteID, $itemID);
     */
    function sofunc_get_sys_exfield_data($target, $siteID, $itemID) {
        switch ($target) {
            case 'CUSTOMER':
                return M('tcustomer_ex_' . $siteID)->where("userID=$itemID")->find();
            case 'PRODUCT':
                return M('tproduct_ex_' . $siteID)->where("productID=$itemID")->find();
                break;
            default:
                return false;
        }
    }

    /**
     * 获取规范的Url参数sort
     * <br />如: $sortby = sofunc_get_orderby(I('sort'))
     * @param string $sort
     * @return boolean
     * @since 1.0 2015-2-2 by sutroon
     */
    function sofunc_get_orderby($sort) {
        if ($sort) {
            switch ($sort[0]) {
                case 'D':
                    return substr($sort, 1) . ' DESC';
                case 'A':
                    return substr($sort, 1);
                default:
                    return $sort;
            }
        }
        return false;
    }

    /**
     * 查询树形列表并分页
     * @param string $table 数据表名称
     * @param string $where 查询条件
     * @param string $strpage 分页条
     * @param int $parentID 父级编号
     * @param array $options 可选参数,包含 int:PAGESIZE, string:FIELDS, string:ORDERBY, array:PAGEPARAMS
     * @return array
     * @since 1.0 2014-8-21 by sutroon
     */
    function sofunc_get_paging_tree($table, $where, &$strpage, $parentID = 0, $options = array()) {
        $options = array_merge(array('PAGESIZE' => C('USR_PAGESIZE'), 'FIELDS' => '*', 'ORDERBY' => 'id', 'PAGEPARAMS' => null), $options);
        $orderby = $options['ORDERBY'] ? ' order by ' . $options['ORDERBY'] : '';
        $search = is_array($where) ? sofunc_convert_array_search_to_string($where) : $where;
        if ($search) {
            $search = ' where ' . str_replace('{0}', $parentID, $search);
        }
        $M = M();
        $list = $M->query("select count(" . $options['FIELDS'] . ") as n from $table $search");
        $count = $list[0]['n'];

        $Page = create_page($count, $options['PAGESIZE'], is_array($options['PAGEPARAMS']) ? $options['PAGEPARAMS'] : sofunc_convert_tpexp_to_querystring($where));
        $strpage = $Page->show();

        $list = $M->query('select ' . $options['FIELDS'] . " from $table $search $orderby limit " . $Page->firstRow . ',' . $Page->listRows);
        $arr = array();
        if ($list) {
            foreach ($list as $row) {
                $row['treeLevel'] = 1;
                $arr[] = $row;
                func_sofunc_get_paging_tree($table, $options['FIELDS'], $orderby, $row['id'], $arr, 2);
            }
        }
        return $arr;
    }

// 2014-8-21 by sutroon
    function func_sofunc_get_paging_tree($table, $fields, $orderby, $parentID, &$arr, $n = 1) {
        $list = M()->query('select ' . $fields . " from $table where parentID=" . $parentID . $orderby);
        if ($list) {
            foreach ($list as $row) {
                $row['treeLevel'] = $n;
                $arr[] = $row;
                func_sofunc_get_paging_tree($table, $fields, $orderby, $row['id'], $arr, $n + 1);
            }
        }
    }

    /**
     * 获取树形数据表
     * @param string $table 数据表名称
     * @param string $where 查询条件,占位符{0},如: parentID={0} and name like '%abc%'
     * @param int $parentID 父级编号,默认是0
     * @param array $options 可选参数, 包含: string:FIELDS, string:ORDERBY
     * @return array 返回包含sub子数组的数组
     * @since 1.0 2014-10-28 by sutroon
     * @example sofunc_get_tree_table('tuser_permission', "parentID={0}", 0, array('ORDERBY' => 'id asc'));
     */
    function sofunc_get_tree_table($table, $where = 'parentID={0}', $parentID = 0, $options = array()) {
        $opts = array('FIELDS' => '*', 'ORDERBY' => 'id');
        if ($options) {
            $opts = array_merge($opts, $options);
        }
        $orderby = $options['ORDERBY'] ? ' order by ' . $opts['ORDERBY'] : '';
        $search = is_array($where) ? sofunc_convert_array_search_to_string($where) : $where;
        if ($search) {
            $search = ' where ' . str_replace('{0}', $parentID, $search);
        }
        $list = M()->query('select ' . $opts['FIELDS'] . " from $table $search $orderby");
        /*
          if (is_array($where)) {
          if (isset($where['parentID'])) {
          $where['parentID'] = str_replace('{0}', $parentID, $where['parentID']);
          }
          } else {
          $where = str_replace('{0}', $parentID, $where);
          }
          $M = M($table)->where($where)->field($opts['FIELDS']);
          if ($opts['ORDERBY']) {
          $M->order($opts['ORDERBY']);
          }
          $list = $M->select();
          echo 'select '.$opts['FIELDS'].' from '.$table.' where '.$search;
         */
        $arr = array();
        if ($list) {
            foreach ($list as $row) {
                $row['sub'] = sofunc_get_tree_table($table, $where, $row['id'], $options);
                $arr[] = $row;
            }
        }
        return $arr;
    }

    /**
     * 将get_tree_table()返回的列表转换为<option />标签字符串
     * @param array $list get_tree_table()返回的结果集(包含sub字段)
     * @param string $value 值
     * @param int $level 级数,无需理会
     * @return string
     * @since 1.0 2014-11-3 by sutroon
     * @example
     * $list = get_tree_table($table, $where, $parentID, $options);
     * return '<select name="' . $name . '">' . get_tree_option_from_treetable($list, $value) . '</select>';
     */
    function sofunc_get_tree_option_from_treetable($list, $value = '', $level = 0) {
        $str = '';
        if ($list) {
            $id_name = '';
            $value_name = '';
            foreach ($list as $row) {
                if (!$id_name) {
                    $keys = array_keys($row);
                    $id_name = $keys[0];
                    $value_name = $keys[1];
                }
                $str .= '<option value="' . $row[$id_name] . '"' . ($value && $value == $row[$id_name] ? ' selected="selected"' : '') . '>' . str_pad('', $level * 2, '--') . $row[$value_name] . '</option>';
                if ($row['sub']) {
                    $str .= sofunc_get_tree_option_from_treetable($row['sub'], $value, $level + 1);
                }
            }
        }
        return $str;
    }

}
